layui.define(['element', 'api', 'fast_config','utils','form'], function(exports) {
    "use strict";

    /**
     * Button component
     * */
    var MOD_NAME = 'object_design',
        $ = layui.jquery,
        api = layui.api,
        fast_config = layui.fast_config,
        form = layui.form,
        utils = layui.utils,
        rowIndex
    ;

    var object_design = function(opt) {
        this.option = opt;
    };

    /**
     * Button start loading
     * */
    object_design.prototype.render = function(opt) {

        var option = {
            elem: opt.elem,
            initData:opt.initData,
            grid: null,
            gridSetting:{
                colModel: opt.gridSetting.colModel,
                defaultRowData: opt.gridSetting.defaultRowData
            }
        }

        var grid;
        var metaName;
        var colums=[],defaultRowData=option.gridSetting.defaultRowData;

        var operationCol = { title: "操作", editable: false, width: 220, sortable: false,
            render: function (ui) {
                // debugger
                if(ui.rowIndx==0){
                    return `<a title="复制" class='copy_btn'><span class="icon copy"></span></a><span class="divider"></span><a title="下移" class='down_btn'><span class="icon move_down"></span></a>`;
                }
                if(ui.rowIndx==option.initData.length-1){
                    return `<a title="复制" class='copy_btn'><span class="icon copy"></span></a><span class="divider"></span><a title="上移" class='up_btn'><span class="icon move_up"></span></a>`;
                }
                if(ui.rowIndx>0 && ui.rowIndx<option.initData.length-1){
                    return `<a title="复制" class='copy_btn'><span class="icon copy"></span></a><span class="divider"></span><a title="上移" class='up_btn'><span class="icon move_up"></span></a><span class="divider"></span><a title="下移" class='down_btn'><span class="icon move_down"></span></a>`;
                    // return `<button type='button' class='copy_btn'></button>\<button type='button' class='up_btn'></button>\<button type='button' class='down_btn'></button>
                    //         <button type='button' class="edit_btn"></button>`;
                }
            },
            postRender: function (ui) {

                let copyData = {...{},...ui.rowData},
                    copyIndx=ui.rowIndx+1,
                    grid = this,
                    $cell = grid.getCell(ui);
                copyData.fieldComment = copyData.fieldComment+"copy";
                copyData.fieldName = copyData.fieldName+"copy";

                if(copyData.columnName !== undefined && copyData.columnName !== "" ){
                    copyData.columnName = copyData.columnName+"copy";
                }
                copyData.pq_rowselect=undefined;copyData.state=false;

                //copy button
                $cell.find(".copy_btn")
                    // .button({ icons: { primary: 'ui-icon-copy'} })
                    .bind("click", function (evt) {
                        grid.addRow({ newRow: copyData, rowIndx: copyIndx });
                    });

                //up button
                $cell.find(".up_btn")
                    // .button({ icons: { primary: 'ui-icon-arrowthick-1-n'} })
                    .bind("click", function (evt) {
                        // debugger
                        let upIndx = ui.rowIndx-1,cruIndx = ui.rowIndx,
                            upData = grid.getRowData({rowIndx: upIndx});
                        grid.deleteRow({rowIndx: upIndx});
                        grid.addRow({newRow:upData,rowIndx:cruIndx})

                    });
                //down button
                $cell.find(".down_btn")
                    // .button({ icons: { primary: 'ui-icon-arrowthick-1-s'} })
                    .bind("click", function (evt) {
                        let downIndx = ui.rowIndx+1,cruIndx = ui.rowIndx,
                            downData = grid.getRowData({rowIndx: cruIndx});
                        grid.deleteRow({rowIndx: cruIndx});
                        grid.addRow({newRow:downData,rowIndx:downIndx})
                    });
            }
        }

        if(option.gridSetting.colModel.length>0 && option.gridSetting.colModel[option.gridSetting.colModel.length-1].title!=='操作'){
            option.gridSetting.colModel[option.gridSetting.colModel.length] = operationCol;
            colums = option.gridSetting.colModel;
        }

        var obj = {
            hwrap: false,
            virtualX: true,
            rowBorders: false,
            trackModel: { on: true }, //to turn on the track changes.
            selectionModel: { type: null },
            toolbar: {
                items: [
                    {   type: 'button', icon: 'ui-icon-plus', label: '',
                        listener: function () {
                            //append empty row at the end.
                            let i = grid.getData().length+1,rData={};
                            for (let key of Object.keys(defaultRowData)){
                                let value = defaultRowData[key];
                                if(key === "fieldComment" || key ==="fieldName"){
                                    rData[key] = value+i;
                                }else{
                                    rData[key] = value;
                                }
                            }
                            let rowData = rData; //default row
                            let rowIndx = grid.addRow( { rowData: rowData, checkEditable: true });
                            grid.goToPage({ rowIndx: rowIndx });
                            grid.editFirstCellInRow({ rowIndx: rowIndx });
                        }
                    },
                    {   type: 'button', icon: 'ui-icon-close', label: '',
                        listener: function () {
                            //debugger
                            if(rowIndex !=null){
                                layer.confirm('确认删除选中数据？', {
                                    title:"删除字段",
                                    btn: ['确认','取消'] //按钮
                                }, function(){
                                    let selarray = grid.selection({ type: 'row', method: 'getSelection' }),
                                        checked=[];
                                    for (var i = 0, len = selarray.length; i < len; i++) {
                                        checked.push({rowIndx:selarray[i].rowIndx});
                                    }
                                    grid.deleteRow({rowList: checked});

                                    rowIndex = null;
                                    layer.closeAll();
                                    layer.msg('操作成功');
                                }, function(){
                                    layer.closeAll();
                                });
                            }else{
                                layer.alert('请先选择行！');
                            }
                        }
                    }
                ]
            },
            scrollModel: {
                autoFit: true
            },
            selectChange: function (evt, ui) {
                console.log('selectChange', ui);
                let address = ui.selection.address();
                rowIndex = address;
            },
            swipeModel: { on: false, type: null },
            editor: {
                select: true
            },
            bootstrap: { on : false },
            height: 'flex',
            showTitle: false,
            title: "<b>"+metaName+"</b>",
            history: function (evt, ui) {
                var $tb = this.toolbar();
                if (ui.canUndo != null) {
                    $("button.changes", $tb).button("option", { disabled: !ui.canUndo });
                }
                if (ui.canRedo != null) {
                    $("button:contains('Redo')", $tb).button("option", "disabled", !ui.canRedo);
                }
                $("button:contains('Undo')", $tb).button("option", { label: 'Undo (' + ui.num_undo + ')' });
                $("button:contains('Redo')", $tb).button("option", { label: 'Redo (' + ui.num_redo + ')' });
            },
            colModel: colums,
            postRenderInterval: -1, //call postRender synchronously.
            // pageModel: { type: "remote", rPP: 20 },
            create: function(){
                this.widget().pqTooltip();
            },
            dataModel:{data: option.initData}
        };

        var gridModel = function (){
            var self = this
            self.editRow = function( rd ){
                self.reset();
            };

            self.reset = function(){
                copy( master, self.company);
                self.focus(true);
            };
        }

        grid = pq.grid( option.elem, obj );

        option.grid = grid;

        return new object_design(option);
    }


    exports(MOD_NAME, new object_design());
});
